package org.muninn.niagara.structures;

import javax.baja.fox.BFoxProxySession;
import javax.baja.naming.BHost;
import javax.baja.naming.BOrd;
import javax.baja.sys.BObject;

public class BJaceNetwork extends BObject
{
  private BPointTree[] network;
  private String[] ips, usernames, passwords;
  private int[] ports;
  
  public BJaceNetwork(String[] ips, int[] ports, String[] usernames, String[] passwords) throws Exception
  {
    this.ips = ips;
    this.ports = ports;
    this.usernames = usernames;
    this.passwords = passwords;
    
    network = new BPointTree[ips.length];
    
    for (int i = 0; (i < passwords.length && i < ports.length && i < usernames.length && i < passwords.length); i++)
    {
      BFoxProxySession session = BFoxProxySession.make((BHost) BOrd.make("ip:" + ips[i]).get(), ports[i], usernames[i], passwords[i]);
      session.engageNoRetry("session");
      network[i] = new BPointTree(BOrd.make("station:|slot:/Drivers").resolve(session).getComponent());
      session.disengage("session");
    }
  }
  
  public boolean reconnect(String ip) throws Exception
  {
    for (int i = 0; i < ips.length; i++)
    {
      if (ips[i].equals(ip))
      {
        BFoxProxySession session = BFoxProxySession.make((BHost) BOrd.make("ip:" + ips[i]).get(), ports[i], usernames[i], passwords[i]);
        session.engageNoRetry("session");
        if (session.isEngaged("session"))
        {
          network[i] = new BPointTree(BOrd.make("station:|slot:/Drivers").resolve(session).getComponent());
          return true;
        }
        
        else
          return false;
      }
    }
    
    return false;
  }
  
  public void changeIp(String old, String gnu) { changeInfo(old, gnu, -1, null, null); }
  
  public void changePort(String ip, int port) { changeInfo(ip, null, port, null, null); }
  
  public void changeUser(String ip, String user) { changeInfo(ip, null, -1, user, null); }
  
  public void changePass(String ip, String pass) { changeInfo(ip, null, -1, null, pass); }
  
  public void changeInfo(String old, String ip, int port, String user, String pass)
  {
    for (int i = 0; i < ips.length; i++)
    {
      if (ips[i].equals(old))
      {
        if (ip != null)
          ips[i] = ip;
        if (port != -1)
          ports[i] = port;
        if (user != null)
          usernames[i] = user;
        if (pass != null)
          passwords[i] = pass;
      }
    }
  }
}
